from rest_framework import viewsets
from rest_framework.response import Response
from django.db.models import Count
from core.models import Tag
from core.serializers.tag import TagSerializer

class TagViewSet(viewsets.ReadOnlyModelViewSet):
    """标签视图集"""
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    lookup_field = 'slug'
    pagination_class = None  # 禁用分页

    def get_queryset(self):
        """获取查询集并添加文档数量统计"""
        return super().get_queryset().annotate(
            document_count=Count('documents')
        )

    def list(self, request, *args, **kwargs):
        """获取标签列表"""
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        })

    def retrieve(self, request, *args, **kwargs):
        """获取标签详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        }) 